#!/bin/bash

################################################################################
# 脚本名称: 3-deploy-service.sh
# 执行位置: 生产服务器
# 功能描述: 拉取基础镜像 → 本地编译 → 构建业务镜像 → 运行
# 作者: 高宇
# 使用方法: bash 3-deploy-service.sh [start|stop|restart|status|logs|compile|build]
################################################################################

set -e

# ============================================================================
# 配置参数
# ============================================================================

# 容器信息
CONTAINER_NAME="hydro-model-service"
IMAGE_NAME="hydro-model-service"
IMAGE_TAG="1.0.0"

# Nexus仓库信息
NEXUS_HOST="172.20.7.86:5001"
NEXUS_USERNAME="admin"
NEXUS_PASSWORD="admin123"
NEXUS_REPO="hydro"

# 基础镜像（从Nexus拉取）
BASE_IMAGE_NAME="${NEXUS_HOST}/${NEXUS_REPO}/hydro-model-base:latest"

# 本地服务镜像名称（不推送Nexus，直接运行）
LOCAL_SERVICE_IMAGE="${IMAGE_NAME}:${IMAGE_TAG}"

# 项目路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

# 端口映射
HOST_PORT="8083"
CONTAINER_PORT="8080"

# 数据卷挂载
HOST_LOG_PATH="./logs"
HOST_TASK_PATH="./task-storage"
HOST_OUTPUT_PATH="./output"

# JVM参数
JAVA_OPTS="-Xms1g -Xmx4g -XX:+UseG1GC"

# ============================================================================
# 颜色输出
# ============================================================================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# ============================================================================
# 登录Nexus
# ============================================================================
login_nexus() {
    print_info "登录Nexus私有仓库..."
    echo "${NEXUS_PASSWORD}" | docker login ${NEXUS_HOST} -u ${NEXUS_USERNAME} --password-stdin
    print_success "登录成功！"
}

# ============================================================================
# 拉取基础镜像
# ============================================================================
pull_base_image() {
    print_info "从Nexus拉取基础镜像: ${BASE_IMAGE_NAME}"
    docker pull ${BASE_IMAGE_NAME}
    print_success "基础镜像拉取完成！"
    docker images | grep hydro-model-base
}

# ============================================================================
# 本地编译项目
# ============================================================================
compile_project() {
    print_info "=========================================="
    print_info "本地编译项目"
    print_info "=========================================="
    
    if [ ! -d "${PROJECT_ROOT}" ]; then
        print_error "项目目录不存在: ${PROJECT_ROOT}"
        exit 1
    fi
    
    cd "${PROJECT_ROOT}"
    
    if ! command -v mvn &> /dev/null; then
        print_error "Maven未安装"
        exit 1
    fi
    
    print_info "开始编译..."
    mvn clean package -DskipTests
    
    if [ ! -f "hydro-model-service/target/hydro-model-service.jar" ]; then
        print_error "JAR文件生成失败"
        exit 1
    fi
    
    print_success "编译完成！"
    ls -lh hydro-model-service/target/hydro-model-service.jar
}

# ============================================================================
# 构建业务镜像
# ============================================================================
build_service_image() {
    print_info "=========================================="
    print_info "构建业务镜像"
    print_info "=========================================="
    
    if [ ! -f "${SCRIPT_DIR}/Dockerfile" ]; then
        print_error "Dockerfile不存在: ${SCRIPT_DIR}/Dockerfile"
        exit 1
    fi
    
    if [ ! -f "${PROJECT_ROOT}/hydro-model-service/target/hydro-model-service.jar" ]; then
        print_warning "JAR文件不存在，先编译项目..."
        compile_project
    fi
    
    cd "${PROJECT_ROOT}"
    
    print_info "构建Docker镜像: ${LOCAL_SERVICE_IMAGE}"
    docker build -f docker/Dockerfile -t ${LOCAL_SERVICE_IMAGE} .
    
    docker tag ${LOCAL_SERVICE_IMAGE} ${IMAGE_NAME}:latest
    
    print_success "镜像构建完成！"
    docker images | grep ${IMAGE_NAME}
}

# ============================================================================
# 创建必要的目录
# ============================================================================
create_directories() {
    print_info "创建数据卷目录..."
    mkdir -p ${HOST_LOG_PATH}
    mkdir -p ${HOST_TASK_PATH}
    mkdir -p ${HOST_OUTPUT_PATH}
    print_success "目录创建完成！"
}

# ============================================================================
# 停止并删除旧容器
# ============================================================================
stop_container() {
    if [ "$(docker ps -aq -f name=${CONTAINER_NAME})" ]; then
        print_warning "停止旧容器: ${CONTAINER_NAME}"
        docker stop ${CONTAINER_NAME} || true
        docker rm ${CONTAINER_NAME} || true
        print_success "旧容器已删除！"
    else
        print_info "没有运行中的容器"
    fi
}

# ============================================================================
# 启动容器
# ============================================================================
start_container() {
    print_info "启动新容器: ${CONTAINER_NAME}"
    
    docker run -d \
        --name ${CONTAINER_NAME} \
        --restart=unless-stopped \
        -p ${HOST_PORT}:${CONTAINER_PORT} \
        -v $(pwd)/${HOST_LOG_PATH}:/app/logs \
        -v $(pwd)/${HOST_TASK_PATH}:/app/task-storage \
        -v $(pwd)/${HOST_OUTPUT_PATH}:/app/output \
        -e JAVA_OPTS="${JAVA_OPTS}" \
        -e TZ=Asia/Shanghai \
        ${LOCAL_SERVICE_IMAGE}
    
    print_success "容器启动成功！"
}

# ============================================================================
# 检查容器状态
# ============================================================================
check_status() {
    echo ""
    print_info "容器状态："
    docker ps -a | grep ${CONTAINER_NAME} || print_warning "容器不存在"
    
    echo ""
    print_info "服务健康检查（等待30秒）..."
    sleep 30
    
    if curl -s http://localhost:${HOST_PORT}/actuator/health > /dev/null; then
        print_success "服务健康检查通过！✓"
        echo ""
        print_info "服务访问地址："
        echo "  - Swagger UI: http://localhost:${HOST_PORT}/swagger-ui.html"
        echo "  - API文档: http://localhost:${HOST_PORT}/v3/api-docs"
        echo "  - 健康检查: http://localhost:${HOST_PORT}/actuator/health"
    else
        print_error "服务健康检查失败！请查看日志"
    fi
}

# ============================================================================
# 查看日志
# ============================================================================
show_logs() {
    print_info "查看容器日志（Ctrl+C退出）..."
    docker logs -f ${CONTAINER_NAME}
}

# ============================================================================
# 完整部署流程
# ============================================================================
deploy() {
    echo ""
    echo "╔════════════════════════════════════════════════════════════════╗"
    echo "║                                                                ║"
    echo "║    [脚本3] 生产服务器 - 部署水文模型服务                         ║"
    echo "║                                                                ║"
    echo "╚════════════════════════════════════════════════════════════════╝"
    echo ""
    
    login_nexus
    pull_base_image
    compile_project
    build_service_image
    create_directories
    stop_container
    start_container
    check_status
    
    echo ""
    print_success "╔════════════════════════════════════════════════════════════════╗"
    print_success "║                    部署完成！                                   ║"
    print_success "╚════════════════════════════════════════════════════════════════╝"
    echo ""
    
    print_info "常用命令："
    echo "  查看日志: bash 3-deploy-service.sh logs"
    echo "  查看状态: bash 3-deploy-service.sh status"
    echo "  重启服务: bash 3-deploy-service.sh restart"
    echo "  停止服务: bash 3-deploy-service.sh stop"
    echo "  只编译: bash 3-deploy-service.sh compile"
    echo "  只构建镜像: bash 3-deploy-service.sh build"
    echo ""
}

# ============================================================================
# 主函数
# ============================================================================
case "${1:-start}" in
    start)
        deploy
        ;;
    stop)
        stop_container
        ;;
    restart)
        stop_container
        sleep 2
        start_container
        check_status
        ;;
    status)
        check_status
        ;;
    logs)
        show_logs
        ;;
    compile)
        compile_project
        ;;
    build)
        login_nexus
        pull_base_image
        compile_project
        build_service_image
        ;;
    *)
        echo "用法: $0 {start|stop|restart|status|logs|compile|build}"
        echo ""
        echo "命令说明："
        echo "  start   - 完整部署流程：拉取基础镜像 → 编译 → 构建 → 运行（默认）"
        echo "  stop    - 停止容器"
        echo "  restart - 重启容器"
        echo "  status  - 查看状态"
        echo "  logs    - 查看日志"
        echo "  compile - 只编译项目"
        echo "  build   - 编译 + 构建镜像（不运行）"
        exit 1
        ;;
esac
